﻿#include "awtk.h"
#include "gesture_lock/gesture_lock.h"
#include "gesture_lock_register.h"

static struct _Ctrl {
    bool_t setting_password;
    str_t password;
} _ctrl;

static ret_t on_reset_password(void *ctx, event_t *e) {
    widget_t *win = WIDGET(ctx);
    widget_t *info = widget_lookup(win, "info", TRUE);

    if (info != NULL) {
        _ctrl.setting_password = TRUE;
        widget_set_text(info, L"请设置密码");
    }

    return RET_OK;
}

static ret_t on_password_entered(void *ctx, event_t *e) {
    value_change_event_t *evt = value_change_event_cast(e);
    widget_t *win = WIDGET(ctx);
    widget_t *info = widget_lookup(win, "info", TRUE);
    const char *pw = value_str(&evt->new_value);

    log_debug("%s(%s)\n", __func__, pw);

    if (_ctrl.setting_password == TRUE) {
        //设置密码
        str_reset(&_ctrl.password);
        str_append(&_ctrl.password, pw);

        _ctrl.setting_password = FALSE;
        widget_set_text(info, L"设置密码成功");
    } else {
        // 校验密码
        bool_t password_valid = str_eq(&_ctrl.password, pw);

        if (password_valid) {
            widget_set_text(info, L"密码正确");
        } else {
            widget_set_text(info, L"密码错误");
        }
    }

    return RET_OK;
}

/**
 * 初始化
 */
ret_t application_init(void) {
    gesture_lock_register();

    widget_t *win = window_open("demo");
    widget_child_on(win, "reset_password", EVT_CLICK, on_reset_password, win);
    widget_child_on(win, "lock", EVT_VALUE_CHANGED, on_password_entered, win);

    _ctrl.setting_password = TRUE;
    str_init(&_ctrl.password, 0);

    return RET_OK;
}

/**
 * 退出
 */
ret_t application_exit(void) {
    log_debug("application_exit\n");
    _ctrl.setting_password = FALSE;
    str_reset(&_ctrl.password);

    return RET_OK;
}
